package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import cloudContact.Common;
import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.FacebookContact;
import cloudContact.DAO.FacebookContactDAO;
import cloudContact.DAO.GoogleContact;
import cloudContact.DAO.GoogleContactDAO;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.util.ServiceException;

/**
 * Servlet implementation class SavePhotoFromFacebook
 */
@WebServlet("/SavePhotoFromFacebook")
public class SavePhotoFromFacebook extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SavePhotoFromFacebook() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Start SavePhotoFromFacebook...");

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				out.println("Error: User is not authorized.");
				return;
			}

			
			
			HttpSession session = request.getSession();
			User user = null;
			try {			
				 user = UserDAO.getInstance().lookup(session.getAttribute("userId").toString());			
			} catch (RollbackException e) {
				e.printStackTrace();
			} catch (MyDAOException e) {
				e.printStackTrace();
			}

			if (user == null) {
				out.println("Error: User not found.");
				return;
			}
			
			GoogleOAuthParameters oauthParameters = GoogleConstant.getGoogleOAuthParameters(user.getGMailAccessToken(), user.getGMailAuthSecrete(), user.getUserId());
		
			
			String contactId = request.getParameter("contactid").replace("\\/", "/").replace("@", "%40");
			String facebookId = request.getParameter("facebookid"); 
			System.out.println("contact ID = " + contactId);
			System.out.println("contact ID = " + facebookId);
			
			GoogleContactDAO gContactDAO = GoogleContactDAO.getInstanceForSession(session.getId(), oauthParameters);
			
			
			GoogleContact contact = gContactDAO.lookup(contactId);
			
			
			if (contact == null)
			{
				throw new MyDAOException("The contact should be there.");
			}
			
			FacebookContactDAO fContactDAO = FacebookContactDAO.getInstance(session.getId(), "me", user.getFacebookAccessToken());
			FacebookContact fcontact = fContactDAO.lookup(facebookId);
			
			contact.setImage(fcontact.getImage());
			
		} catch (OAuthException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (ServiceException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
			System.out.println("Finish SavePhotoFromFacebook.");
		}
	}

}
